<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class DB_Cache
{
	public $ci;
	
	public function __construct()
	{
		$this->ci =& get_instance();
	}
	
	public function dbQueryCache($query,$type='all',$age=300)
	{
		if( function_exists('apc_add') and function_exists('apc_fetch') )
		{
			$name = 'CACHED_'.time().'_'.md5($query);
			$data = apc_fetch($name, $success);
			
			if (!$success) {
				$data = $this->getDataFromDB($query, $type);
				$x = apc_add($name, $data, $age);
			}
			if ($this->ci->adodb->debug){
				if( $success ){
					echo "SQL_Cached $name: " . substr( strtolower($query), 0, 100) . '<br>';
				}
			}
			return $data;
		}
		else
		{
			return $this->getDataFromDB($query,$type);	
		}
	}
	
	protected function getDataFromDB($sql,$type="all")
	{
		if ($type == 'all') {
			$data = $this->ci->adodb->GetAll($sql);
		} elseif ($type == 'one') {
			$data = $this->ci->adodb->GetOne($sql);
		} elseif ($type == 'row') {
			$data = $this->ci->adodb->GetRow($sql);
		} elseif ($type == 'col') {
			$data = $this->ci->adodb->GetCol($sql);
		} elseif ($type == 'assoc') {
			$data = $this->ci->adodb->GetAssoc($sql);
		}
		return $data;	
	}
}